<?php

class ViewCartController extends FController {
	public function actionIndex($alias = null) {
		$model = new CheckOutForm();
		$type = Yii::app()->request->getParam('type',null);
		if (isset($_POST) && isset($_POST['CheckOutForm'])) {
			$model->attributes = $_POST['CheckOutForm'];
			$model->state = $_POST['CheckOutForm']['state'];
			$model->emailPaypal = $_POST['CheckOutForm']['emailPaypal'];
			
			$shop = MyShopping::model()->findByAttributes(array('my_shopping_id'=>$_POST['idShoppingCart']));
			
			// dump($_POST,false);
			// dump($model->attributes);
			if ($model->validate()) {
				
				// dump(Yii::app()->session['listcart']);
				if(Yii::app()->session['listcart'] != null){
				
					foreach(Yii::app()->session['listcart'] as $key=>$cart){
						$carts = new Carts;
						$carts->attributes = $model->attributes;
						if(empty($shop)){
							$newModel = new MyShopping;
							$newModel->my_shopping_id = $_POST['idShoppingCart'];
							$newModel->save();
							$carts->my_shopping_id = $newModel->my_shopping_id;
						}else{
							$carts->my_shopping_id = $shop->my_shopping_id;
						}
						
						$pending = Configs::model()->findByAttributes(array('type'=>0));
						$carts->config_id = $pending->id;
						$carts->product_id = $cart['product_id'];
						$carts->emailPaypal = $model->emailPaypal;
						$carts->quantity =  $cart['quantity'];
						$carts->price =  $cart['amount'];
						$carts->created =  time();
						$carts->options =  $cart['os0'];
						$carts->save();
						
						
					}
					
				}
				

					
				if($model->payment != "Paypal"){
					$this->redirect('/home');
				}
				// Yii::app()->session['cart'] = null;
				// Yii::app()->session['listcart'] = null;
				Yii::app()->user->setFlash('success', "Validate infomation successfully!");
				$this->redirect('/products/viewCart?type=paypal');
					
				
				// dump($carts->attributes,false);
			}else{
				// dump($model->validate());
			}
		}
		

		$this->render('index', array(
			'model'		=> $model,
			'type'		=> $type,
			'arrStatus'				=> CheckOutForm::getState(),
			'arrTermsConditions'	=> CheckOutForm::getTermsConditions()
		));
	}
}